package com.xcx.baseManger.handler;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xcx.baseManger.helper.Message;
import com.xcx.baseManger.helper.User;
import com.xcx.baseManger.service.MessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;


@Component
public class MyHandler extends TextWebSocketHandler {
    @Autowired
    private MessageService messageService;
    private static  final ObjectMapper MAPPER = new ObjectMapper();
    //
    private static final Map<String, WebSocketSession> SESSION = new HashMap<>();



        //客户端建立链接后的消息
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = (String) session.getAttributes().get("ByUsername");

        //把用户信息存到session中
        SESSION.put(username,session);

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //获取到链接用户名
        String Byusername = (String) session.getAttributes().get("ByUsername");
        User fromUser = messageService.findByUsername(Byusername);

        //message格式传递json toUsername:xxx   msg:xxx
        JsonNode jsonNode = MAPPER.readTree(message.getPayload());
        String toUsername = jsonNode.get("toUsername").asText();
        String msg = jsonNode.get("msg").asText();
        User usernameTo = messageService.findByUsername(toUsername);



        //构建message类
        Message messages = new Message();
        //如果是mongodb内的表不能get，set，如果是实体类就可以get，set拿到对应实体类的值一起保存到mngodb
        messages.setFrom(fromUser);
        messages.setTo(usernameTo);
        messages.setMsg(msg);
        //保存到mongdb中
        Message saveMessage = messageService.saveMessage(messages);

        //判断to用户是否在线
        WebSocketSession toSession = SESSION.get(toUsername);
        if (toSession != null && toSession.isOpen()){
            toSession.sendMessage(new TextMessage(MAPPER.writeValueAsString(messages)));
            //更新消息状态已读
            messageService.updateMessageState(messages.getId(),2);

        }


//        //获取到消息
//        System.out.println("获取消息 》》" + message.getPayload());
//        //向客户端发送消息
//        session.sendMessage(new TextMessage("消息已收到"));



    }


    //断开链接后返回消息


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("断开链接");
    }
}
